package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;
import com.webserver.vo.Article;
import com.webserver.vo.User;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理与文章相关的业务
 * @Author Alex
 */
@Controller
public class ArticleController {
    private static Logger log = Logger.getLogger(UserController.class);

    //所有用户信息所保存的目录
    public static final String ARTICLE_DIR = "./articles/";

    static{
        File dir =new File(ARTICLE_DIR);
        if (!dir.exists()){
            dir.mkdirs();
        }
    }

    @RequestMapping("/myweb/writeArticle")
    public void writeArticle(HttpServletRequest request,HttpServletResponse response){
        log.info("开始发表文章");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        if (title==null||author==null||content==null){
            File file = new File("./webapps/myweb/article_fail.html");
            response.setEntity(file);
            return;
        }
        try (
                FileOutputStream fos = new FileOutputStream(ARTICLE_DIR+title+".obj");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            Article article = new Article(title,author,content);
            oos.writeObject(article);
            File file = new File("./webapps/myweb/article_success.html");
            response.setEntity(file);
            return;
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        log.info("文章发表处理完毕");
    }

    @RequestMapping("/myweb/showAllArticle")
    public void showAllArticle(HttpServletRequest request,HttpServletResponse response) throws IOException {
        log.info("动态显示文章");
        //1将file目录中的文件读取出来
        List<Article> artList = new ArrayList<>();
        //将文件反序列化
        File dir = new File(ARTICLE_DIR);
        File[] artArr = dir.listFiles(f->f.getName().endsWith(".obj"));
        for (File art:artArr){
            try (
                FileInputStream fis = new FileInputStream(art);
                ObjectInputStream ois = new ObjectInputStream(fis)
            ){
                artList.add((Article)ois.readObject());
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }
        PrintWriter pw = response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">\n");
        pw.println("<head>\n");
        pw.println("<meta charset=\"UTF-8\">\n");
        pw.println("<title>文章列表</title>\n");
        pw.println("</head>\n");
        pw.println("<body>\n");
        pw.println("<center>\n");
        pw.println("<h1>文章列表</h1>");
        pw.println("<table border=\"1\">");
        pw.println("<tr>");
        pw.println("<td align=\"center\">标题</td>");
        pw.println("<td align=\"center\">作者</td>");
        pw.println("<td align=\"center\">操作</td>");
        pw.println("</tr>");
        for (Article art:artList){
            pw.println("<tr>");
            pw.println("<td align=\"center\"><a href=\"/myweb/showArticle?title="+art.getTitle()+"\">"+art.getTitle()+"</td>");
            //通过title获取文件名字将文件反序列化输出成页面
            pw.println("<td align=\"center\">"+art.getAuthor()+"</td>");
            //通过title获取文件名将文件删除
            pw.println("<td align=\"center\"><a href=\"/myweb/deleteArticle?title="+art.getTitle()+"\">"+"删除文章"+"</td>");
            pw.println("</tr>");
        }
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");
        //3 设置响应头Content-Type,告知浏览器这些动态数据是一个页面
        response.setContentType("text/html");
        log.info("文章显示完毕");
    }

    /**
     * 显示单独一篇文章内容
     * @param request
     * @param response
     */
    @RequestMapping("/myweb/showArticle")
    public void showArticle(HttpServletRequest request,HttpServletResponse response){
        log.info("开始显示一篇文章");
        //获取文件名字,并转码
        String fileName =request.getParameter("title")+".obj";
        //转码
        System.out.println("要显示的文件名:"+fileName);
        File dir = new File(ARTICLE_DIR);
        File[] allArt = dir.listFiles(f->f.getName().equals(fileName));
        if (allArt.length==0){
            log.info("找不到该文件");
            File notFound = new File("./webapps/root/404.html");
            response.setEntity(notFound);
            return;
        }
        //由于本程序不支持文件同名,因此allArt数组中最多只有一个文件
        File artFile= allArt[0];
        Article article = null;
        try (
                FileInputStream fis = new FileInputStream(artFile);
                ObjectInputStream ois = new ObjectInputStream(fis);
        ){
            article= (Article) ois.readObject();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        PrintWriter pw = response.getWriter();
        pw.println("<!DOCTYPE html>");
        pw.println("<html lang=\"en\">");
        pw.println("<head>");
        pw.println("<meta charset=\"UTF-8\">");
        pw.println("<title>文章</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<center>");
        pw.println("<h1>文章详情</h1>");
        //将整个页面装入form表单
        pw.println("<form action=\"/myweb/modifyArticle\" method=\"get\">");
        pw.println("<table border=\"1\">");
        pw.println("<tr>");
        pw.println("<td>标题</td>");
        pw.println("<td><textarea name=\"title\" cols=\"30\" rows=\"1\">"+article.getTitle()+"</textarea></td>");
        pw.println("</tr>");
        pw.println("<tr>");
        pw.println("<td>作者</td>");
        pw.println("<td><textarea name=\"author\" cols=\"30\" rows=\"1\">"+article.getAuthor()+"</textarea></td>");
        pw.println("</tr>");
        pw.println("<tr>");
        pw.println("<td colspan=\"2\">");
        pw.println("<textarea name=\"content\" cols=\"50\" rows=\"10\">"+article.getContent()+"</textarea>");
        pw.println("</td>");
        pw.println("</tr>");
        pw.println("<tr>");
        pw.println("<td colspan=\"2\" align=\"center\">");
        pw.println("<input type=\"submit\" value=\"修改\" onclick=\"alert('修改成功')\">");
        pw.println();
        pw.println("</tr>");
        pw.println("</form>");
        pw.println("</table>");
        pw.println("</center>");
        pw.println("</body>");
        pw.println("</html>");

        log.info("文章显示完毕");
    }

    @RequestMapping("/myweb/deleteArticle")
    public void deleteArticle(HttpServletRequest request,HttpServletResponse response){
        log.info("开始删除文章");
        //点击修改之后,通过?右边获取 title author content
        //1通过title找到对应的文件
        String title = request.getParameter("title");
        String oldFileName = title+".obj";
        //2删除.obj文件
        File dir = new File(ARTICLE_DIR);
        File[] oldFile = dir.listFiles(f->f.getName().equals(oldFileName));
        if(oldFile.length>0){
            oldFile[0].delete();
        }
        //跳转到修改成功页面
        File sucFile = new File("./webapps/myweb/delete_success.html");
        response.setEntity(sucFile);

        log.info("文章删除成功");
    }

    @RequestMapping("/myweb/modifyArticle")
    public void modifyArticle(HttpServletRequest request,HttpServletResponse response){
        log.info("开始修改文章");
        //点击修改之后,通过?右边获取 title author content
        //1通过title找到对应的文件
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content =request.getParameter("content");

        Article newArt = new Article(title,author,content);
        String oldFileName = title+".obj";
        //2反序列化修改.obj文件,将新的content放回去
        File dir = new File(ARTICLE_DIR);
        File[] oldFile = dir.listFiles(f->f.getName().equals(oldFileName));
        try (
                FileOutputStream fos = new FileOutputStream(oldFile[0]);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(newArt);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        //跳转到修改成功页面
        File SucFile = new File("./webapps/myweb/modify_success.html");
        response.setEntity(SucFile);
        log.info("文章修改成功");
    }
}
